<script setup lang="ts">
import { h, onMounted, ref, watch } from 'vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import { listPictureVoByPageUsingPost } from '@/api/pictureController.ts'
import { formatSize } from '@/utils'
import { EditOutlined, BarChartOutlined, TeamOutlined } from '@ant-design/icons-vue'
import PictureList from '@/components/PictureList.vue'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import BatchEditPictureModal from '@/components/BatchEditPictureModal.vue'
import { SPACE_ROLE_ENUM, SPACE_TYPE_ENUM, SPACE_TYPE_MAP } from '@/constant/space.ts'
import { useSpaceUserRoleStore } from '@/stores/SpaceUserRoleStore.ts'

const props = defineProps<{
  id: string | number
}>()
const space = ref<API.SpaceVO>({})

// 获取空间详情
const fetchSpaceDetail = async () => {
  try {
    const res = await getSpaceVoByIdUsingGet({
      id: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    } else {
      message.error('获取空间详情失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取空间详情失败：' + e.message)
  }
}

// 数据
const dataList = ref([])
const total = ref(0)
const loading = ref(true)

// 搜索条件
const searchParams = ref<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数
const onPageChange = (page: any, pageSize: any) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = {
    spaceId: props.id,
    ...searchParams.value,
  }
  const res = await listPictureVoByPageUsingPost(params)
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

// 搜索
const onSearch = (newSearchParams: API.PictureQueryRequest) => {
  searchParams.value = {
    ...searchParams.value,
    ...newSearchParams,
    current: 1,
  }
  fetchData()
}

// 分享弹窗引用
const batchEditPictureModalRef = ref()

// 批量编辑成功后，刷新数据
const onBatchEditPictureSuccess = () => {
  fetchData()
}

// 打开批量编辑弹窗
const doBatchEdit = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}

const spaceUserRoleStore = useSpaceUserRoleStore()

// 页面加载时请求一次
onMounted(() => {
  spaceUserRoleStore.fetchSpaceUserRole(props.id)
  fetchSpaceDetail()
  fetchData()
})

watch(
  () => props.id,
  (newSpaceId) => {
    fetchSpaceDetail()
    fetchData()
    spaceUserRoleStore.fetchSpaceUserRole(props.id)
  },
)
</script>

<template>
  <!-- 空间信息 -->
  <a-flex justify="space-between" style="margin-bottom: 16px">
    <h2>{{ space.spaceName }}（{{ SPACE_TYPE_MAP[space.spaceType] }}）</h2>
    <a-space size="middle">
      <a-button
        type="primary"
        :href="`/add_picture?spaceId=${id}`"
        target="_blank"
        v-if="
          space.spaceType === SPACE_TYPE_ENUM.PRIVATE ||
          (space.spaceType === SPACE_TYPE_ENUM.TEAM &&
            spaceUserRoleStore.getSpaceUserRole() != SPACE_ROLE_ENUM.VIEWER)
        "
      >
        + 创建图片
      </a-button>
      <a-button
        type="primary"
        ghost
        :icon="h(TeamOutlined)"
        :href="`/spaceUserManage/${id}`"
        target="_blank"
        v-if="
          space.spaceType === SPACE_TYPE_ENUM.TEAM &&
          spaceUserRoleStore.getSpaceUserRole() === SPACE_ROLE_ENUM.ADMIN
        "
      >
        成员管理
      </a-button>
      <a-button
        type="primary"
        ghost
        :icon="h(BarChartOutlined)"
        :href="`/space_analyze?spaceId=${id}`"
        target="_blank"
      >
        空间分析
      </a-button>
      <a-button
        :icon="h(EditOutlined)"
        @click="doBatchEdit"
        v-if="
          space.spaceType === SPACE_TYPE_ENUM.PRIVATE ||
          (space.spaceType === SPACE_TYPE_ENUM.TEAM &&
            spaceUserRoleStore.getSpaceUserRole() != SPACE_ROLE_ENUM.VIEWER)
        "
      >
        批量编辑
      </a-button>
      <a-tooltip :title="`占用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxSize)}`">
        <a-progress
          type="circle"
          :percent="((space.totalSize * 100) / space.maxSize).toFixed(1)"
          :size="42"
        />
      </a-tooltip>
    </a-space>
  </a-flex>
  <!-- 搜索表单 -->
  <PictureSearchForm :onSearch="onSearch" />
  <!-- 图片列表 -->
  <PictureList
    :dataList="dataList"
    :showOp="true"
    :onReload="fetchData"
    :loading="loading"
    :canEdit="spaceUserRoleStore.getSpaceUserRole() != SPACE_ROLE_ENUM.VIEWER"
    :canDelete="spaceUserRoleStore.getSpaceUserRole() != SPACE_ROLE_ENUM.VIEWER"
  />
  <a-pagination
    style="text-align: right"
    v-model:current="searchParams.current"
    v-model:pageSize="searchParams.pageSize"
    :total="total"
    :show-total="() => `图片总数 ${total} / ${space.maxCount}`"
    @change="onPageChange"
  />
  <BatchEditPictureModal
    ref="batchEditPictureModalRef"
    :spaceId="id"
    :pictureList="dataList"
    :onSuccess="onBatchEditPictureSuccess"
  />
</template>

<style scoped></style>
